﻿
using System;
using System.Collections.Generic;
using System.Linq;
using PsqlDotnet.Enums;
namespace PsqlDotnet.Model.Schema
{
    public class ForeignKey : IConstraint
    {
        public ForeignKey(ForeignKeySettings settings)
        {
            if (settings == null)
                throw new NullReferenceException("Illegal null-reference settings");
            if (!settings.Validate())
                throw new ArgumentException("Non-valid settings");

            Name = settings.Name;
            SourceTable = settings.SourceTable;
            SourceColumns = settings.SourceColumns;
            ReferencedTable = settings.ReferencedTable;
            ReferencedColumns = settings.ReferencedColumns;
            MatchType = settings.MatchType;
            DeleteAction = settings.DeleteAction;
            UpdateAction = settings.UpdateAction;
        }

        #region IRelation Members

        public ConstraintType RelationType
        {
            get
            {
                return ConstraintType.ForeignKey;
            }
        }

        public string Name { get; private set; }

        public string SourceTable { get; private set; }

        #endregion

        public IEnumerable<string> SourceColumns { get; private set; }

        public string ReferencedTable { get; private set; }

        public IEnumerable<string> ReferencedColumns { get; private set; }

        public ForeignKeyMatchEnum MatchType { get; private set; }

        public ForeignKeyActionEnum DeleteAction { get; private set; }

        public ForeignKeyActionEnum UpdateAction { get; private set; }
    }

    public class ForeignKeySettings
    {
        public string Name { get; set; }

        public string SourceTable { get; set; }

        public IEnumerable<string> SourceColumns { get; set; }

        public string ReferencedTable { get; set; }

        public IEnumerable<string> ReferencedColumns { get; set; }

        public ForeignKeyMatchEnum MatchType { get; set; }

        public ForeignKeyActionEnum DeleteAction { get; set; }

        public ForeignKeyActionEnum UpdateAction { get; set; }

        public bool Validate()
        {
            bool success = !String.IsNullOrWhiteSpace(Name);
            success &= !String.IsNullOrWhiteSpace(SourceTable);
            success &= SourceColumns != null && SourceColumns.Count() > 0;
            success &= !String.IsNullOrWhiteSpace(ReferencedTable);
            success &= ReferencedColumns != null && ReferencedColumns.Count() > 0;

            return success;
        }
    }
}
